<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-05 11:50:55
 * @LastEditTime: 2023-07-25 16:34:33
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Middleware;

use App\Models\Role;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;

class Permission
    {
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct(Auth $auth)
        {

        $this->auth = $auth;
        }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next)
        {
        if (class_exists(getController())) {
            //登录session
            $token = app("token");
            if ($token->user->id != 1) {
                //访问接口
                $api = app('api');
                //is_visit 是否开启访问权限
                if ($api->is_visit == 1) {
                    $exists = Role::whereHas("user", function ($query) use ($token)
                        {
                        $query->where("users.id", $token->user->id);
                        })
                        ->whereHas("api", function ($query) use ($api)
                            {
                            $query->where("basedata_api.id", $api->id);
                            })
                        ->exists();

                    if (!$exists) {
                        fail("没有[{$api->model}/{$api->controller}/{$api->action}]权限！请申请接口权限！", '500');
                        }
                    }
                }
            }
        else {
            fail("页面不存在", '404');
            }

        return $next($request);
        }
    }